// 请求头
var header = {
  "content-type": "application/json;charset=utf-8", // 请求数据类型根据需求自行更改
  // "content-type":"'application/x-www-form-urlencoded'",
  os: "android/ios",
  version: "1.0.0",
  'authorization': wx.getStorageSync('token'),
  'x-requested-uniapp': 'uniapp'
};

// url请求前缀
const BaseUrl = "http://localhost:8890/"

/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  // console.log("请求参数:", params);
  return params;
}

/**
 * 供外部get请求调用
 */
function get(url, params, onSuccess, onFailed, useToken) {
  // console.log("请求方式：", "GET");
  request(url, params, "GET", onSuccess, onFailed, useToken);
}

/**
* 供外部post请求调用
*/
function post(url, params, onSuccess, onFailed, useToken) {
  // console.log("请求方式：", "POST");
  request(url, params, "POST", onSuccess, onFailed, useToken);
}

var tokenOnece = 0;

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 * @useToken 是否使用token（不使用token调用时填入任意参数即可  如1）
 */
function request(url, params, method, onSuccess, onFailed, useToken) {
  if (tokenOnece != 0 ) {
    // console.log("hhh");
    header.authorization = wx.getStorageSync('token');
    // console.log(header.authorization)
  } 
  tokenOnece = tokenOnece + 1;
  // console.log(tokenOnece)
  // console.log(header)
  // console.log(wx.getStorageSync('token'))
  wx.request({
    url: BaseUrl + url,
    method: method,
    data: dealParams(params),
    header: header,
    success: function (res) {
      onSuccess(res)
    },
    fail: function (error) {
        console.log(error)
    },
  })
}

module.exports = {
  postRequest: post,
  getRequest: get
};